from dataclasses import dataclass
from uuid import UUID

from flask import request
from injector import inject

from internal.schema import ApiToolSchema, CreateApiToolSchema, ProviderRsp, ToolsRsp
from internal.schema.api_tool_schema import GetApiToolProvidersWithPageReq, GetApiToolProvidersWithPageResp
from internal.service import APIToolService
from pkg.pageinator.pageinator import PageModel
from pkg.resp.response import success_message, success_json, validate_error_json


@inject
@dataclass
class APIToolsHanlder:
    api_tool_ser: APIToolService

    def validator_schema(self):
        req = ApiToolSchema()
        if not req.validate():
            return validate_error_json(erros=req.errors)
        self.api_tool_ser.validator_schema(req.openapi_schema.data)
        return success_message("参数校验成功")

    def create_api_tools(self):
        req = CreateApiToolSchema()
        if not req.validate():
            return validate_error_json(erros=req.errors)
        self.api_tool_ser.create_tool_provider(req)
        return success_message("添加成功")

    def get_tool_provider(self, provider_id: UUID):
        api_tool_provider = self.api_tool_ser.get_tool_provider(provider_id)
        resp = ProviderRsp()
        return success_json(resp.dump(api_tool_provider))

    def get_tool(self, provider_id: UUID, tool_name: str):
        api_tool = self.api_tool_ser.get_tool(provider_id, tool_name)
        tool = ToolsRsp()
        return success_json(tool.dump(api_tool))

    def delete_tool_provider(self, provider_id: UUID):
        self.api_tool_ser.delete_tool_provider(provider_id)
        return success_message("删除成功")

    def get_api_tool_providers_with_page(self):
        req = GetApiToolProvidersWithPageReq(request.args)
        if not req.validate():
            return validate_error_json(erros=req.errors)
        api_tool_providers, paginator = self.api_tool_ser.get_api_tool_providers_with_page(req)
        resp = GetApiToolProvidersWithPageResp(many=True)
        return success_json(PageModel(list=resp.dump(api_tool_providers), paginator=paginator))

    def update_tool_provider(self, provider_id: UUID):
        req = CreateApiToolSchema()
        if not req.validate():
            return validate_error_json(erros=req.errors)
        self.api_tool_ser.update_api_tool_provider(req, provider_id)
        return success_message("修改成功")
    